
//HAL

//BSP
#include "bsp/bsp_key.h"
//OS
#include "jxos_public.h"

#if (JXOS_STD_APP_KEY_TASK_ENABLE == 1)
static JXOS_EVENT_HANDLE key_press_event;

static swtime_type key_scan_swt;
static swtime_type key_multi_click_swt;

static uint8_t key_msg_buff[KEY_MULTI_TASK_MSG_BUFF_LEN];
static JXOS_MSG_HANDLE key_msg;

static uint8_t key_multi_click_count;
static uint8_t key_multi_click_keynum;

void (*std_app_key_multi_task_hal_init_callback)(void) = 0;
uint8_t (*std_app_key_multi_task_hal_read_pin_level_callback)(uint8_t key_num) = 0;

static void key_task(uint8_t task_id, void * parameter)
{
	uint8_t msg_itme;
	if(jxos_event_wait(key_press_event) == 1){
		sys_software_timer_task_restart_timer(key_scan_swt);
		bsp_key_scan_handler();
		if(bsp_key_all_release() == 1){
			sys_software_timer_task_stop_timer(key_scan_swt);
		}
	}
	if(sys_software_timer_task_check_overtime_timer(key_scan_swt) == 1){
		bsp_key_scan_handler();
		if(bsp_key_all_release() == 1){
			sys_software_timer_task_stop_timer(key_scan_swt);
		}
	}
	if(sys_software_timer_task_check_overtime_timer(key_multi_click_swt) == 1){
		sys_software_timer_task_stop_timer(key_multi_click_swt);
		key_multi_click_count = 0;
		key_multi_click_keynum = 0xff;
	}
}

/******************************/
void std_app_key_multi_task_key_press_interrupt_handler(void)
{
	jxos_event_set(key_press_event);
}

static void key_task_key_press_callback_handler(uint8_t key_num)
{
	uint8_t msg_itme;
	
	sys_software_timer_task_restart_timer(key_multi_click_swt);
	if(key_multi_click_keynum != key_num){
		key_multi_click_count = 0;
		key_multi_click_keynum = key_num;
	}

	if(key_multi_click_count < 0x0f){
		key_multi_click_count++;
		msg_itme = key_multi_click_keynum<<4;
		msg_itme |= key_multi_click_count;
		jxos_msg_send(key_msg, &msg_itme);
	}
}

static void key_task_key_long_press_callback_handler(uint8_t key_num)
{
	uint8_t msg_itme;
	msg_itme = key_num<<4;
	msg_itme |= 0;
	jxos_msg_send(key_msg, &msg_itme);
}

/******************************/
void std_app_key_multi_task_init(void)
{
	key_multi_click_count = 0;
	key_multi_click_keynum = 0xff;

	//HAL
//	if(std_app_key_task_hal_init_callback != 0){
//		std_app_key_task_hal_init_callback();
//	}

	//BSP
	bsp_key_init(std_app_key_task_hal_init_callback,
				std_app_key_task_hal_read_pin_level_callback,
				0,
				key_task_key_press_callback_handler,
				0,
				key_task_key_long_press_callback_handler);

	//OS
	jxos_task_create(key_task, "key_multi", 0);
	key_press_event = jxos_event_create();
    key_msg = jxos_msg_create(key_msg_buff, 32, 1, "std_app_key_multi_msg");

	//LIB

	//SYS TASK
	key_scan_swt = sys_software_timer_task_new_timer();
	sys_software_timer_task_set_timer(key_scan_swt, KEY_TASK_SCAN_TIME);

	key_multi_click_swt = sys_software_timer_task_new_timer();
	sys_software_timer_task_set_timer(key_multi_click_swt, KEY_TASK_MULTI_CLICK_TIME);
}
#endif

